package com.passer.toolbox.common.password.encryption;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class Encrypt {
    public String encrypt(String plainText) {
        StringBuilder stringBuilder = new StringBuilder();
        BigDecimal two = new BigDecimal("2");
        BigDecimal value;
        byte[] bytes = plainText.getBytes(StandardCharsets.UTF_8);
        for (byte aByte : bytes) {
            value = new BigDecimal(aByte);
            if (aByte == 0) {
                stringBuilder.append("@");
                continue;
            }
            stringBuilder.append(value.abs().divide(two, 1, RoundingMode.HALF_UP));
            if (aByte > 0) {
                stringBuilder.append("]");
            } else {
                stringBuilder.append("[");
            }
        }
        return stringBuilder.toString();
    }

    public String decrypt(String encryptedText) {
        List<Byte> bytes = new ArrayList<>();
        char[] charArray = encryptedText.toCharArray();
        List<Character> charList = new ArrayList<>();
        for (char c : charArray) {
            if ('@' == c) {
                bytes.add((byte) 0);
                continue;
            }
            charList.add(c);
            if (']' == c || '[' == c) {
                bytes.add(getSourceNumber(charList));
                charList.clear();
            }
        }
        byte[] byteArray = new byte[bytes.size()];
        for (int i = 0; i < byteArray.length; i++) {
            byteArray[i] = bytes.get(i);
        }
        return new String(byteArray, StandardCharsets.UTF_8);
    }


    private byte getSourceNumber(List<Character> charList) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < charList.size() - 1; i++) {
            stringBuilder.append(charList.get(i));
        }
        double v = Double.parseDouble(stringBuilder.toString()) * 2D;
        if ('[' == charList.get(charList.size() - 1)) {
            v = v * -1;
        }
        return (byte) v;
    }
}
